package com.quanyan.place.task.tracker;

import com.github.ltsopensource.core.domain.Action;
import com.github.ltsopensource.tasktracker.Result;
import com.github.ltsopensource.tasktracker.logger.BizLogger;
import com.github.ltsopensource.tasktracker.runner.JobContext;
import com.github.ltsopensource.tasktracker.runner.JobRunner;
import com.github.ltsopensource.tasktracker.runner.LtsLoggerFactory;
import com.quanyan.place.biz.ISearchService;
import com.quanyan.place.cache.PlaceRedisTemplate;
import com.quanyan.place.constants.PlaceConstants;
import com.quanyan.redisCluster.utils.RedisConstants;
import com.quanyan.redisCluster.utils.RedisKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

/**
 * Created by Kingson.chan on 2016/9/6 0006.
 */
@Component("syncPlaceInfoSolrTask")
public class SyncPlaceInfoSolrTask implements JobRunner {

    private static final Logger logger = LoggerFactory.getLogger(SyncPlaceInfoSolrTask.class);

    @Autowired
    private ISearchService searchService;

    @Autowired
    PlaceRedisTemplate placeRedisTemplate;

    @Override
    public Result run(JobContext jobContext) throws Throwable {

        try {
            RedisKey redisKey = new RedisKey(RedisConstants.PLACE_FAMILY_KEY, PlaceConstants.PLACE_SYNC_SOLR_PREFIX );
            if (placeRedisTemplate.exists(redisKey)){
                Set<Integer> placeIdSet = (Set<Integer>) placeRedisTemplate.get(redisKey);
                if (null != placeIdSet && placeIdSet.size() > 0){
                    Iterator iterator = placeIdSet.iterator();
                    while(iterator.hasNext()){
                        Integer placeId = (Integer) iterator.next();
                        try {
                            searchService.addPlaceSaleIndex(placeId);
                        }catch (Exception e){
                            logger.error("syncPlaceInfoSolrTask执行增加索引失败！");
                            return new Result(Action.EXECUTE_EXCEPTION, "syncPlaceInfoSolrTask执行增加索引失败!"+e.getMessage());
                        }
                        logger.info("场馆信息修改已同步到solr placeId:" + placeId);
                    }
                    placeIdSet.clear();
                    placeRedisTemplate.setWithExpireTime(redisKey, placeIdSet, 24 * 60 * 60);
                    //placeRedisTemplate.delteKey(redisKey);
                }
            }

            // 会发送到 LTS (JobTracker上)
            BizLogger bizLogger = LtsLoggerFactory.getBizLogger();
            bizLogger.info("更新场馆索引任务执行成功。");
        } catch (Exception e) {
            logger.info("Run job failed!", e);
            return new Result(Action.EXECUTE_LATER, "更新场馆索引任务执行失败，"+e.getMessage());
        }
        return new Result(Action.EXECUTE_SUCCESS, "更新场馆索引任务执行成功。");
    }
}
